import puppeteer from 'puppeteer-extra';
import StealthPlugin from 'puppeteer-extra-plugin-stealth';

// Apply the stealth plugin to Puppeteer
puppeteer.use(StealthPlugin());

// Utility function for random delays with TypeScript typing
const delay = (ms: number): Promise<void> =>
  new Promise((resolve) => setTimeout(resolve, ms));

// Main async function
(async (): Promise<void> => {
  // Launch the browser with options typed
  const browser = await puppeteer.launch({
    headless: true,
    args: ['--proxy-server=http://your-proxy-ip:port'], // Replace with your proxy
  });

  // Create a new page
  const page = await browser.newPage();

  // Set realistic browser settings
  await page.setUserAgent(
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  );
  await page.setViewport({ width: 1920, height: 1080 });

  // Block unnecessary resources
  await page.setRequestInterception(true);
  page.on('request', (request) => {
    if (['image', 'stylesheet'].includes(request.resourceType())) {
      request.abort();
    } else {
      request.continue();
    }
  });

  // Navigate to the website and simulate human behavior
  await page.goto('https://example.com', { waitUntil: 'networkidle2' });
  await delay(Math.random() * 1000 + 500); // Random delay between 500-1500ms

  // Scroll the page
  await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));

  // Simulate mouse movement
  await page.mouse.move(500, 300, { steps: 10 });

  // Extract data with type assertion
  const data = await page.evaluate((): string | null => {
    const element = document.querySelector('h1');
    return element ? element.innerText : null;
  });
  console.log(data);

  // Clean up
  await browser.close();
})();
